/**
 * @description  产品组定义
 * @author shenhong
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Transfer, message, Row, Col, Select, Modal, Table, Checkbox } from 'antd';
import { ContentPackage, DATA_ENTRY, TableC, PrimaryC, AdvancedSearch, FormItemLayout } from '../../../comps';
import myStyle from './index.less';
import uuid from 'es6-uuid';

const FormItem = Form.Item;
@Form.create()
class ProductGroupDefinition extends PureComponent {
  constructor() {
    super();
    this.data = [];
    this.state = {
      isShow: false, // 是否展示model框
      isEdit: false, // 是否编辑
      targetKeys: [], // 穿梭框内已选数据
      dataSource: [], // 表格数据
      columns: [
        { dataIndex: 'portfolioName', title: '名称', key: 'portfolioName' },
        { dataIndex: 'creator', title: '创建者', key: 'creator' },
        { dataIndex: 'productNum', title: '产品数量', key: 'productNum' },
        // { dataIndex: 'institutionModelName', title: '机构', key: 'institutionModelName' },
      ],
      pageInfo: {}, // 表格分页参数
      expandRow: [], // 表格展开行id
      record: {},
      value: {},
      currentUser: {}, // 当前登录用户信息
      expiredProducts: 'false', // 是否勾选到期自动出组
      changeStatus: false,
      options: [], // 获取产品名称下拉
      productName: '',
      productNameLoading: false,
    };
  }

  componentDidMount() {
    const { expiredProducts } = this.state;
    this.setState({
      expiredProducts,
    });
    this.getDatas();
    const { dispatch } = this.props;
    dispatch({
      type: 'productGroupDefinitionM/getTranData',
      payload: {
        tradeModel: 'BOOKKEEPING_MODE,COMMAND_MODE,VALUATION_BOOKKEEPING_MODEL', // 产品组定义不支持选估值解析模式的产品
      },
    });
    dispatch({
      type: 'couponPoolDefinitionM/getUserInfo',
      payload: {
        userId: localStorage.getItem('antd-pro-userId'),
      },
      callback: (res) => {
        this.setState({
          currentUser: res,
          expiredProducts,
        });
      },
    });

    // 获取产品名称下拉数据
    this.getProductNameDataSource();
  }

  getProductNameDataSource = (productName, cb) => {
    this.props.dispatch({
      type: 'productManageM/getList',
      payload: {
        currentPage: 1,
        numInPage: 20,
        ...(productName ? { productName } : {}),
      },
      callback: (res) => {
        console.log('获取下拉数据', res);
        const options = res.dataSource.map((item) => {
          console.log('item', item);
          const obj = { value: item.id, title: `${item.code} - ${item.productName}` };
          return obj;
        });
        console.log('options', options);
        this.setState(
          {
            options,
          },
          () => {
            cb && cb();
          },
        );
      },
    });
  };

  // 初始化页面数据
  getDatas = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'productGroupDefinitionM/getData',
      payload: {
        currentPage: 1,
        numInPage: 20,
      },
      callback: (res) => {
        const datas = res.dataSource;
        const { pageInfo } = res;
        // const columns = this.columns;
        const newData = this.changeDatas1(datas);
        this.setState({
          dataSource: newData,
          // columns: columns,
          pageInfo,
        });
      },
    });
    dispatch({
      type: 'productGroupDefinitionM/getCondition',
      payload: {},
    });
  };

  // 表格数据增加唯一标识
  changeDatas33 = (datas, e) => {
    const arr = [];
    datas.forEach((item) => {
      item.useId = item.id || item.key;
      item.id = uuid(32);
      if (e && item.portfolioName.indexOf(e) != -1) {
        if (item.children && item.children.length > 0) {
          // this.changeDatas33(item.children);
        }
        arr.push(item);
      }
    });
    return arr;
  };

  changeDatas1 = (datas) => {
    const arr = [];
    datas.forEach((item) => {
      item.useId = item.id || item.key;
      item.id = uuid(32);
      arr.push(item);
      if (item.children && item.children.length > 0) {
        this.changeDatas1(item.children);
      }
    });
    return arr;
  };

  // 点击新增
  addInfo = () => {
    this.setState(
      {
        isEdit: false,
        targetKeys: [],
        changeStatus: false,
        expiredProducts: 'false',
      },
      () => {
        this.setState({
          isShow: true,
        });
      },
    );
  };

  // 点击查询
  handleSearch = (e) => {
    console.log('查询传参e', e);
    const { dispatch } = this.props;
    console.log('productName', e.productName);

    if (e || e.portfolioName || e.productName) {
      //  如果有查询条件传给后台，否则按默认查询条件
      dispatch({
        type: 'productGroupDefinitionM/getData',
        payload: {
          name: e.portfolioName || '',
          productCode: e.productName || '',
          currentPage: 1,
          numInPage: 20,
        },
        callback: (res) => {
          const datas = res.dataSource;
          const { pageInfo } = res;
          const newData = this.changeDatas1(datas);
          this.setState({
            dataSource: newData,
            pageInfo,
          });
        },
      });
    } else {
      dispatch({
        type: 'productGroupDefinitionM/getData',
        payload: {
          currentPage: 1,
          numInPage: 20,
        },
        callback: (res) => {
          const datas = res.dataSource;
          // const columns = res.columns;
          const { pageInfo } = res;
          const newData = this.changeDatas1(datas);
          this.setState({
            dataSource: newData,
            // columns: columns,
            pageInfo,
          });
        },
      });
    }
  };

  //  点击修改调用
  edit = (record) => {
    const { children, expiredProducts } = record;
    this.setState({
      record,
      isShow: true,
      isEdit: true,
      targetKeys: this.changeDatas2(children),
      expiredProducts,
      changeStatus: expiredProducts === 'true',
    });
  };

  // 模态框点击确定事件
  handleOk = () => {
    const { dispatch, form } = this.props;
    const { isEdit, targetKeys, expiredProducts, changeStatus } = this.state;
    const that = this;
    if (isEdit) {
      // 调用修改接口
      form.validateFields(['name', 'createUser', 'institutions'], (err, fieldsValue) => {
        if (err) {
          return;
        }
        const data = {
          id: this.state.record.useId,
          name: form.getFieldValue('name'),
          institutionModelIds: form.getFieldValue('institutionModelIds'),
          portfolioInfoIds: targetKeys,
          expiredProducts,
          changeStatus,
        };
        dispatch({
          type: 'productGroupDefinitionM/editData',
          payload: { ...data },
        }).then((res) => {
          if (res.code == 0) {
            message.success('修改成功');
            this.setState({ isShow: false, isEdit: false });
            form.resetFields();
            that.getDatas();
          } else {
            message.error(res.msg);
          }
        });
      });
    } else {
      // 调用新增接口
      form.validateFields(['name', 'createUser', 'institutionModelIds'], (err, fieldsValue) => {
        if (err) {
          return;
        }
        const data = {
          name: form.getFieldValue('name'),
          institutionModelIds: form.getFieldValue('institutionModelIds'),
          portfolioInfoIds: targetKeys,
          expiredProducts,
          changeStatus,
        };
        dispatch({
          type: 'productGroupDefinitionM/addData',
          payload: { ...data },
        }).then((res) => {
          if (res.code == 0) {
            message.success('添加成功');
            this.setState({ isShow: false, isEdit: false });
            form.resetFields();
            that.getDatas();
          } else {
            message.error(res.msg);
          }
        });
      });
    }
  };

  // 优化表格&&添加操作列
  actionColumns = (e) => {
    const { dispatch, form } = this.props;
    const that = this;
    const arr = e;
    if (e && e.length && e[e.length - 1].title != '操作') {
      arr.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        operates: [
          {
            title: '编辑',
            onClick: (record) => this.edit(record),
            rules: {
              disabled: { relation: 'and', items: [{ key: 'edit', value: [true], relation: ['!='] }] },
              hide: { relation: 'and', items: [{ key: 'edit', value: [undefined], relation: ['='] }] },
            },
          },
          {
            title: '删除',
            onClick: (record, index) => {
              dispatch({
                type: 'productGroupDefinitionM/deleteData',
                payload: { id: record.useId },
              }).then((res) => {
                if (res.code == 0) {
                  message.success('删除成功');
                  form.resetFields();
                  that.getDatas();
                } else {
                  message.error(res.msg);
                }
              });
            },
            rules: {
              disabled: { relation: 'and', items: [{ key: 'edit', value: [true], relation: ['!='] }] },
              hide: { relation: 'and', items: [{ key: 'edit', value: [undefined], relation: ['='] }] },
            },
          },
        ],
      });
    }
    return arr;
  };

  // 表格行扩展回填数据
  finData = (record, dataSource) => {
    const datas = dataSource;
    datas.map((item) => {
      if (item.id == record.id) {
        item = record;
      } else if (item.children && item.children.length) {
        this.finData(record, item.children);
      }
    });
    this.setState({
      dataSource: datas,
    });
  };

  // 获取点击行接口返回数据的children
  getArr = (newData) => {
    let data = [];
    newData.map((item) => {
      data = item.children;
    });
    return data;
  };

  // 表格行扩展
  onExpandChange = (expanded, record) => {
    this.data = [];
    const rowdata = JSON.parse(JSON.stringify(this.state.expandRow));
    if (expanded) {
      rowdata.push(record.id.toString(16)); // 为表格行添加唯一性标识
      this.setState({
        // 记录展开的行
        expandRow: rowdata,
      });
      if (record.product) {
        const { dispatch } = this.props;
        const { dataSource } = this.state;
        dispatch({
          type: 'productGroupDefinitionM/getRowData',
          payload: { rootId: record.useId },
          callback: (res) => {
            const newData = this.changeDatas1(res);
            const useChildren = this.getArr(newData); // 获取点击行接口返回数据的children
            record.children = useChildren;
            this.finData(record, dataSource); // 表格行扩展回填数据
          },
        });
      }
    } else {
      // 展开行闭合时更改数组
      const newRowData = rowdata.filter((item) => item !== record.id);
      this.setState({
        // 记录展开的行
        expandRow: newRowData,
      });
    }
  };

  // 分页信息
  onTableChange = (current, size) => {
    const { dispatch } = this.props;
    const { value } = this.state;
    const datas =
      value && value.portfolioName
        ? {
            name: value.portfolioName,
            currentPage: current,
            numInPage: size,
          }
        : {
            currentPage: current,
            numInPage: size,
          };
    dispatch({
      type: 'productGroupDefinitionM/getData',
      payload: datas,
      callback: (res) => {
        const datas = res.dataSource;
        // const columns = res.columns;
        const { pageInfo } = res;
        const newData = this.changeDatas1(datas);
        this.setState({
          dataSource: newData,
          // columns: columns,
          pageInfo,
        });
      },
    });
  };

  // 表格内容
  tableRender = () => {
    const { dataSource, columns, pageInfo } = this.state;
    const { loading } = this.props;
    const newcolumns = this.actionColumns(columns);
    return (
      <div>
        <div style={{ marginTop: '10px', marginBottom: '10px' }}>
          <PrimaryC title='新增' onClick={this.addInfo} />
        </div>
        <TableC
          columns={newcolumns}
          dataSource={dataSource}
          rowKey='id'
          selfScrollY={true}
          loading={loading}
          expandedRowKeys={this.state.expandRow}
          onExpand={(expanded, record) => this.onExpandChange(expanded, record)} // 点击行展开事件
          current={pageInfo.currentPage}
          total={pageInfo.total}
          pageSize={pageInfo.numInPage}
          onShowSizeChange={(current, size) => this.onTableChange(current, size)}
          onPageChange={(page, pageSize) => this.onTableChange(page, pageSize)}
        />
      </div>
    );
  };

  // 将接口返回数据更改成穿梭框数据格式
  changeDatas = (e) => {
    const arr = [];
    e?.map((item) => {
      arr.push({
        title: `${item.value}-${item.title}`,
        key: item.value,
        description: `${item.value}-${item.title}`,
      });
    });
    return arr;
  };

  // 穿梭框数据格式2，修改时将children产品id放入数组中
  changeDatas2 = (e) => {
    const arr = [];
    e.map((item) => {
      arr.push(item.portfolioCode);
    });
    return arr;
  };

  // 穿梭框改变事件
  handleChange = (nextTargetKeys, direction, moveKeys) => {
    this.setState({ targetKeys: nextTargetKeys }); // 将穿梭框改变的值存入state
  };

  filterOption = (inputValue, option) => option.description.indexOf(inputValue) > -1;

  // 新增&&编辑模态框内容
  showModal = () => {
    const {
      form: { getFieldDecorator },
      couponPoolDefinitionM: { currentUser },
      productGroupDefinitionM,
    } = this.props;
    const { isEdit, record } = this.state;
    const { transFormData, conditionData } = productGroupDefinitionM;
    const datas = this.changeDatas(transFormData);
    const props1 = {
      visible: this.state.isShow,
      onOk: () => this.handleOk(),
      onCancel: () => {
        this.setState({ isShow: false });
      },
      title: isEdit ? '编辑产品组' : '新建产品组',
      width: 732,
    };
    return (
      <Modal {...props1} key={record.id} className={myStyle.ModalArea} destroyOnClose={true}>
        <div>
          <Form>
            <Row>
              <Col span={12}>
                <FormItem label={'产品组名称'} {...FormItemLayout}>
                  {getFieldDecorator('name', {
                    initialValue: isEdit ? record.portfolioName : null,
                    rules: [{ required: true, message: `请输入` }],
                  })(<Input placeholder='请输入' />)}
                </FormItem>
              </Col>
              <Col span={12} className='rowArea'>
                <FormItem label={'创建人'} {...FormItemLayout}>
                  {getFieldDecorator('createUser', {
                    initialValue: isEdit ? record.creator : currentUser.name,
                  })(<Input disabled={true} />)}
                </FormItem>
              </Col>
              <Col span={12} className={myStyle.checkAutoOut}>
                <Checkbox onChange={this.onChangeConfirm} checked={this.state.changeStatus}>
                  到期产品自动出组
                </Checkbox>
              </Col>
            </Row>
          </Form>
          <div style={{ marginTop: '4px' }}>
            <Transfer
              dataSource={datas}
              showSearch={true}
              filterOption={this.filterOption}
              targetKeys={this.state.targetKeys}
              onChange={this.handleChange}
              render={(item) => item.title}
            />
          </div>
        </div>
      </Modal>
    );
  };

  // 【到期产品自动出组】点击选中
  onChangeConfirm = (e) => {
    let expiredProducts = '';
    let changeStatus = false;
    if (e.target.checked) {
      expiredProducts = 'true';
      changeStatus = true;
    } else {
      expiredProducts = 'false';
      changeStatus = false;
    }
    this.setState({
      expiredProducts,
      changeStatus,
    });
  };

  render() {
    const { options } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'portfolioName',
          title: '产品组名称',
          type: DATA_ENTRY.INPUT,
        },
        {
          dataIndex: 'productName',
          title: '产品名称',
          type: DATA_ENTRY.SELECT,
          allowClear: true,
          // onChange: (e) => {
          //   const productCode = e;
          //   this.setState({
          //     productCode,
          //   });
          // },
          dataSource: options,
          filterOption: false,
          onSearch: (value) => {
            this.getProductNameDataSource(value);
          },
        },
      ],
      onQuery: (e) => {
        console.log('query e', e);
        this.setState(
          {
            value: e,
          },
          () => this.handleSearch(e),
        );
      },
      onClear: () => {
        const { form } = this.props;
        form.resetFields();
      },
    };
    return (
      <ContentPackage
        title='产品组定义'
        contentHtml={
          <div className={myStyle.bodyArea}>
            <div>
              <AdvancedSearch {...searchProps} onRef={(ref) => (this.inves = ref)} />
            </div>
            {this.tableRender()}
            {this.state.isShow ? this.showModal() : null}
          </div>
        }
      />
    );
  }
}
export default connect(({ productGroupDefinitionM, couponPoolDefinitionM, loading }) => ({
  productGroupDefinitionM,
  couponPoolDefinitionM,
  loading: loading.effects['productGroupDefinitionM/getData'],
}))(ProductGroupDefinition);
